<template>
  <div id="myChart" style="width: 100%;height: 500px"></div>
</template>
<script>

import {getPromise} from "../../api/api";

const echarts = require('echarts/lib/echarts');
require('echarts/lib/component/title');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/legend');
require('echarts/lib/chart/pie');

const getEcharsInfo = async () => {
  console.log(1);
  let res = await getPromise('/sys/echarts/getEchartsCirle');
  console.log(res.data.data);
  console.log(2)
  return res.data.data
}

function genData(count) {
  const legendData = [];
  const seriesData = [];
  for (var i = 0; i < count; i++) {
    legendData.push("");
    seriesData.push({
      name: '',
      value: 0
    });
  }
  return {
    legendData: legendData,
    seriesData: seriesData
  };
}


export default {
  name: 'address',
  data() {
    return {}
  },
  async created() {
    let a = await getEcharsInfo();
    let option = this.getInitCirle(a);
    this.drawLine(option)
  },
  mounted() {
    // this.drawLine();
  },
  methods: {
    drawLine(option) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(document.getElementById('myChart'))

      // 绘制图表
      myChart.setOption(option);
    },

    getInitCirle(a) {
      let myData = a;

      let data = genData(myData.length);
      // 2.将值替换
      for (let i = 0; i < myData.length; i++) {
        data.legendData[i] = myData[i].address;
        data.seriesData[i].value = myData[i].num;
        data.seriesData[i].name = myData[i].address;
      }

      // 将数据项进行替换
      const option = {
        title: {
          text: '用户区域分布',
          subtext: '来自数据库',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: data.legendData
        },
        series: [
          {
            name: '地区',
            type: 'pie',
            radius: '55%',
            center: ['40%', '50%'],
            data: data.seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      return option;
    },
  }
}
</script>

<style scoped>
</style>
